//
//  ScriptData.cpp
//  Phidgets
//
//  Created by Daniel Hazelbaker on 12/14/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#include "ScriptData.h"
#include "SystemDatabase.h"
#include "SqlStatement.h"
#include "SqlValue.h"


//
// Create a new script object by loading the given script ID from the database.
//
ScriptData::ScriptData(unsigned int script_id)
{
    SqlParameters params = SqlParameters();
    SqlStatement *stmt;
    
    
    params["@ScriptID"] = script_id;
    stmt = gSharedDatabase->prepareStatement("SELECT * FROM scripts WHERE script_id = @ScriptID", params);

    if (stmt->NextRow())
    {
        LoadFromStatement(stmt);
    }
    else
        _scriptID = -1;
    
    delete stmt;
}


//
// Create a new script object by loading from the databse.
//
ScriptData::ScriptData(SqlStatement *statement)
{
    LoadFromStatement(statement);
}


//
// Load the internal information about this object from the SqlStatement.
//
void ScriptData::LoadFromStatement(SqlStatement *statement)
{
    _scriptID = (*statement)["script_id"].intValue();
    _name = (*statement)["name"].stringValue();
    _runType = (ScriptRunType)(*statement)["runtype"].intValue();
    _code = (*statement)["code"].stringValue();
}


//
// Save this object to the database.
//
bool ScriptData::Save()
{
    SqlParameters params = SqlParameters();
    SqlStatement *stmt;
    bool status;
    
    
    params["@Name"] = _name;
    params["@RunType"] = _runType;
    params["@Code"] = _code;

    gSharedDatabase->Lock();
    if (_scriptID == -1)
    {
        stmt = gSharedDatabase->prepareStatement("INSERT INTO scripts (name, runtype, code) VALUES (@Name, @RunType, @Code)", params);
        status = stmt->ExecuteNonQuery();
        if (status)
            _scriptID = (int)stmt->LastInsertID();
    }
    else
    {
        params["@ScriptID"] = (int)_scriptID;
        stmt = gSharedDatabase->prepareStatement("UPDATE scripts SET name = @Name, runtype = @RunType, code = @Code WHERE script_id = @ScriptID", params);
        status = stmt->ExecuteNonQuery();
    }
    gSharedDatabase->Unlock();
    
    return status;
}


//
// Delete this object from the database.
//
bool ScriptData::Delete()
{
    SqlParameters params = SqlParameters();
    SqlStatement *stmt;
    bool status;
    

    //
    // Make sure we are a valid script object.
    //
    if (_scriptID == -1)
        return false;

    params["@ScriptID"] = (int)_scriptID;
    
    gSharedDatabase->Lock();
    stmt = gSharedDatabase->prepareStatement("DELETE FROM scripts WHERE script_id = @ScriptID", params);
    status = stmt->ExecuteNonQuery();
    gSharedDatabase->Unlock();
    
    return status;
}


